using System;
using System.Collections;
using System.Collections.Specialized;
using Commonplace.Domain;
using System.Collections.Generic;

namespace Commonplace
{
	/// <summary>
	/// Summary description for CachedConfig.
	/// </summary>
	public class CachedConfig
	{
		string _defaultLicense = string.Empty;
		bool _addToWatch = false;
		bool _checkNewVersion = true;
		List<License> _licenses = new List<License>();
		bool _useInfoTemplate = true;
        WikiConnectionConfig _wikiConfig = new WikiConnectionConfig();

		static CachedConfig _instance = new CachedConfig();

		public bool WatchPages { get { return _addToWatch; } }
		public string DefaultLicense { get { return _defaultLicense; } }
		public bool HasDefaultLicense 
		{
			get { return (string.Empty == _defaultLicense); }
		}
		public bool UseInfoTemplate { get { return _useInfoTemplate; } }
		public bool Autoupdate { get { return _checkNewVersion; } }
        public WikiConnectionConfig WikiConnection { get { return _wikiConfig; } }

        public List<License> Licenses
		{
			get 
			{ 
				return _licenses;
			}
		}

		public static CachedConfig Instance
		{
			get { return _instance; }
		}

		private CachedConfig()
		{
			LoadConfig();
		}

		public void Refresh()
		{
			LoadConfig();
		}

		private void LoadConfig()
		{
			StoredConfig config = new StoredConfig();

            List<string> licenseStrings = config.GetList("licenses");
            _licenses.Clear();
            foreach (string licenseString in licenseStrings)
            {
                if (true == licenseString.Contains("|"))
                    _licenses.Add(new License(licenseString));
            }

			string watchUploads = config["watchuploads"];
			string defaultLicense = config["defaultlicense"];
			string useInfoTemplate = config["useinfotemplate"];
			string checkNewVersion = config["autoupdate"];

            string wiki = config["wiki"];
            if (string.Empty != wiki)
                _wikiConfig = new WikiConnectionConfig(wiki);            

			if ("true" == watchUploads)
				_addToWatch = true;
			else
				_addToWatch = false;

			if ("false" == useInfoTemplate)
				_useInfoTemplate = false;
			else
				_useInfoTemplate = true;

			if ("" == checkNewVersion || "true" == checkNewVersion)
				_checkNewVersion = true;
			else
				_checkNewVersion = false;

			
			if (defaultLicense.Length > 0)
				_defaultLicense = defaultLicense;
			else
				_defaultLicense = string.Empty;

		}

	}
}
